﻿namespace WMS6.BLL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Reflection;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;
    using WMS6.DALFactory;

    public class AuditDataBLL : IBaseInfo
    {
        private static readonly IAuditDataDA auditDataDA = DataAccess.CreateAuditDataDA();
        private static readonly IAuditDefinitionDA auditDefinitionDA = DataAccess.CreateAuditDefinitionDA();
        private static readonly ICommonMethodDA commonMethod = DataAccess.CreateCommonMethod();
        private List<string> dataBaseID;
        private PubParasInfo pubParasInfo;

        public AuditDataBLL()
        {
            this.pubParasInfo = null;
        }

        public AuditDataBLL(string currentWH)
        {
            this.pubParasInfo = null;
            if (!string.IsNullOrEmpty(currentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(currentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001");
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002");
            }
        }

        public AuditDataBLL(PubParasInfo tempPubParasInfo)
        {
            this.pubParasInfo = null;
            if (!string.IsNullOrEmpty(tempPubParasInfo.CurrentWH))
            {
                this.dataBaseID = commonMethod.GetDataBaseID(tempPubParasInfo.CurrentWH);
                if (this.dataBaseID == null)
                {
                    PublicMethod.GetInstance().ShowAlertMessage("C001", this.pubParasInfo.UserLanguage);
                }
                else
                {
                    this.pubParasInfo = new PubParasInfo();
                    this.pubParasInfo = tempPubParasInfo;
                }
            }
            else
            {
                PublicMethod.GetInstance().ShowAlertMessage("C002", this.pubParasInfo.UserLanguage);
            }
        }

        public string Delete(List<string> IDS)
        {
            throw new NotImplementedException();
        }

        public DataSet GetAllInfo()
        {
            throw new NotImplementedException();
        }

        public object GetInfoByID(string id)
        {
            throw new NotImplementedException();
        }

        public DataSet GetInfoByQueryEntity(object obj)
        {
            AuditDataQueryEntity auditDataQuery = obj as AuditDataQueryEntity;
            List<string> sqlWhere = new List<string>();
            string tempWhere = string.Empty;
            string tempWhere2 = string.Empty;
            if (!string.IsNullOrEmpty(auditDataQuery.CreatedBy))
            {
                sqlWhere.Add("  ADA.CREATED_BY " + auditDataQuery.CreatedBy);
            }
            if (!string.IsNullOrEmpty(auditDataQuery.TableName))
            {
                sqlWhere.Add("  ADA.TABLE_NAME " + auditDataQuery.TableName);
            }
            if (!string.IsNullOrEmpty(auditDataQuery.ColName))
            {
                sqlWhere.Add("  ADA.COL_NAME " + auditDataQuery.ColName);
            }
            if (!string.IsNullOrEmpty(auditDataQuery.PrimaryKey))
            {
                sqlWhere.Add(" ADA.PRIMARY_KEY " + auditDataQuery.PrimaryKey);
            }
            if (!string.IsNullOrEmpty(auditDataQuery.StartTime))
            {
                sqlWhere.Add(auditDataQuery.StartTime.Replace("@StartTime@", " ADA.CREATED_DATE "));
            }
            if (!string.IsNullOrEmpty(auditDataQuery.EndTime))
            {
                sqlWhere.Add(auditDataQuery.EndTime.Replace("@EndTime@", " ADA.CREATED_DATE "));
            }
            if (!(string.IsNullOrEmpty(auditDataQuery.ForInsert) || !(auditDataQuery.ForInsert == "Y")))
            {
                tempWhere = " ADA.ACTION = 'Insert' ";
            }
            else
            {
                tempWhere2 = " ADA.ACTION <> 'Insert' ";
            }
            if (!(string.IsNullOrEmpty(auditDataQuery.ForUpdate) || !(auditDataQuery.ForUpdate == "Y")))
            {
                tempWhere = tempWhere + (string.IsNullOrEmpty(tempWhere) ? " ADA.ACTION = 'Update' " : " OR ADA.ACTION = 'Update' ");
            }
            else
            {
                tempWhere2 = tempWhere2 + (string.IsNullOrEmpty(tempWhere2) ? " ADA.ACTION <> 'Update' " : " OR ADA.ACTION <> 'Update' ");
            }
            if (!(string.IsNullOrEmpty(auditDataQuery.ForDelete) || !(auditDataQuery.ForDelete == "Y")))
            {
                tempWhere = tempWhere + (string.IsNullOrEmpty(tempWhere) ? " ADA.ACTION = 'Delete' " : " OR ADA.ACTION = 'Delete' ");
            }
            else
            {
                tempWhere2 = tempWhere2 + (string.IsNullOrEmpty(tempWhere2) ? " ADA.ACTION <> 'Delete' " : " OR ADA.ACTION <> 'Delete' ");
            }
            if (!string.IsNullOrEmpty(tempWhere))
            {
                tempWhere = "(" + tempWhere + ")";
                sqlWhere.Add(tempWhere);
            }
            if (!string.IsNullOrEmpty(tempWhere2))
            {
                tempWhere2 = "(" + tempWhere2 + ")";
                sqlWhere.Add(tempWhere2);
            }
            return auditDataDA.GetAuditDataByQueryList(sqlWhere, auditDataQuery, this.dataBaseID[0]);
        }

        public string Insert(object obj)
        {
            throw new NotImplementedException();
        }

        public void InsertAuditData<T>(T oldValue, T newValue, string auditAction, string createdBy, string tableName, string whLoginID)
        {
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                this.InsertAuditData<T>(dataBase, tran, oldValue, newValue, auditAction, createdBy, tableName, whLoginID);
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(ex, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
        }

        public void InsertAuditData<T>(DataBase dataBase, DbTransaction tran, T oldValue, T newValue, string auditAction, string createdBy, string tableName, List<string> whLoginIDs)
        {
            foreach (string whLoginID in whLoginIDs)
            {
                this.InsertAuditData<T>(dataBase, tran, oldValue, newValue, auditAction, createdBy, tableName, whLoginID);
            }
        }

        public void InsertAuditData<T>(DataBase dataBase, DbTransaction tran, T oldValue, T newValue, string auditAction, string createdBy, string tableName, string whLoginID)
        {
            if (ConstUtils.CONST_IS_AUDIT_ACTIVE.ToUpper() == "Y")
            {
                DataSet auditFieldDS = auditDefinitionDA.GetAuditDefinitionByTableNameAndAction(dataBase, tran, tableName, auditAction, whLoginID);
                if ((auditFieldDS != null) && (auditFieldDS.Tables[0].Rows.Count > 0))
                {
                    int index0;
                    PropertyInfo oldValueProperty;
                    PropertyInfo newValueProperty;
                    List<PropertyInfo> oldValuePropertys = null;
                    List<PropertyInfo> newValuePropertys = new List<PropertyInfo>();
                    if (auditAction.ToUpper() != AuditAction.Insert.ToUpper())
                    {
                        oldValuePropertys = new List<PropertyInfo>();
                        PropertyInfo[] tempOldPropertyInfo = oldValue.GetType().GetProperties();
                        for (index0 = 0; index0 < tempOldPropertyInfo.Length; index0++)
                        {
                            oldValuePropertys.Add(tempOldPropertyInfo[index0]);
                        }
                    }
                    if (auditAction.ToUpper() != AuditAction.Delete.ToUpper())
                    {
                        PropertyInfo[] tempNewPropertyInfo = newValue.GetType().GetProperties();
                        for (index0 = 0; index0 < tempNewPropertyInfo.Length; index0++)
                        {
                            newValuePropertys.Add(tempNewPropertyInfo[index0]);
                        }
                    }
                    DataSet primaryKeyDs = auditDefinitionDA.GetPrimaryKeyByTableName(dataBase, tran, tableName, whLoginID);
                    string primaryKeyValue = string.Empty;
                    if ((primaryKeyDs != null) && (primaryKeyDs.Tables[0].Rows.Count > 0))
                    {
                        for (int i = 0; i < primaryKeyDs.Tables[0].Rows.Count; i++)
                        {
                            if (auditAction.ToUpper() != AuditAction.Update.ToUpper())
                            {
                                if ((oldValuePropertys != null) && (oldValuePropertys.Count > 0))
                                {
                                    oldValueProperty = oldValuePropertys.Find(x => x.Name.ToUpper() == primaryKeyDs.Tables[0].Rows[i]["MAPPING_NAME"].ToString().ToUpper());
                                    if ((oldValueProperty != null) && ((oldValueProperty.GetValue(oldValue, null) != null) && (oldValueProperty != null)))
                                    {
                                        primaryKeyValue = primaryKeyValue + oldValueProperty.GetValue(oldValue, null).ToString() + "/";
                                    }
                                }
                                if ((newValuePropertys != null) && (newValuePropertys.Count > 0))
                                {
                                    newValueProperty = newValuePropertys.Find(y => y.Name.ToUpper() == primaryKeyDs.Tables[0].Rows[i]["MAPPING_NAME"].ToString().ToUpper());
                                    if ((newValueProperty != null) && ((newValueProperty.GetValue(newValue, null) != null) && (newValuePropertys != null)))
                                    {
                                        primaryKeyValue = primaryKeyValue + newValueProperty.GetValue(newValue, null).ToString() + "/";
                                    }
                                }
                            }
                            else
                            {
                                oldValueProperty = oldValuePropertys.Find(x => x.Name.ToUpper() == primaryKeyDs.Tables[0].Rows[i]["MAPPING_NAME"].ToString().ToUpper());
                                if ((oldValueProperty != null) && ((oldValueProperty.GetValue(oldValue, null) != null) && (oldValueProperty != null)))
                                {
                                    primaryKeyValue = primaryKeyValue + oldValueProperty.GetValue(oldValue, null).ToString() + "/";
                                }
                            }
                        }
                        primaryKeyValue = (primaryKeyValue.Length > 0) ? primaryKeyValue.Substring(0, primaryKeyValue.Length - 1) : "";
                    }
                    for (int i = 0; i < auditFieldDS.Tables[0].Rows.Count; i++)
                    {
                        string oldValueP = string.Empty;
                        string newValueP = string.Empty;
                        if ((oldValuePropertys != null) && (oldValuePropertys.Count > 0))
                        {
                            oldValueProperty = oldValuePropertys.Find(x => x.Name.ToUpper() == auditFieldDS.Tables[0].Rows[i]["MAPPING_NAME"].ToString().ToUpper());
                            if (oldValueProperty != null)
                            {
                                if (oldValueProperty.Name.ToUpper() == "WHID")
                                {
                                    oldValueProperty.SetValue(oldValue, whLoginID.Substring(0, whLoginID.Length - 1), null);
                                }
                                if ((oldValueProperty.GetValue(oldValue, null) != null) && (oldValueProperty != null))
                                {
                                    oldValueP = oldValueProperty.GetValue(oldValue, null).ToString();
                                }
                            }
                        }
                        if ((newValuePropertys != null) && (newValuePropertys.Count > 0))
                        {
                            newValueProperty = newValuePropertys.Find(y => y.Name.ToUpper() == auditFieldDS.Tables[0].Rows[i]["MAPPING_NAME"].ToString().ToUpper());
                            if (newValueProperty != null)
                            {
                                if (newValueProperty.Name.ToUpper() == "WHID")
                                {
                                    newValueProperty.SetValue(newValue, whLoginID.Substring(0, whLoginID.Length - 1), null);
                                }
                                if ((newValueProperty.GetValue(newValue, null) != null) && (newValuePropertys != null))
                                {
                                    newValueP = newValueProperty.GetValue(newValue, null).ToString();
                                }
                            }
                        }
                        if (oldValueP != newValueP)
                        {
                            AuditDataInfo auditDataInfo = new AuditDataInfo {
                                Action = auditAction,
                                ColName = auditFieldDS.Tables[0].Rows[i]["COL_NAME"].ToString(),
                                CreatedBy = createdBy,
                                CreatedDate = DateTime.Now,
                                NewValue = newValueP,
                                OldValue = oldValueP,
                                PrimaryKey = primaryKeyValue,
                                TableName = tableName
                            };
                            auditDataDA.InsertAuditData(dataBase, tran, auditDataInfo, whLoginID);
                        }
                    }
                }
            }
        }

        public string Update(object obj)
        {
            throw new NotImplementedException();
        }
    }
}

